﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Text.RegularExpressions;
namespace information
{
    public partial class SerialPort : Form
    {
        System.IO.Ports.SerialPort commPort = new System.IO.Ports.SerialPort();
        private StringBuilder builder = new StringBuilder();//避免在事件处理方法中反复的创建，定义到外面。

        public SerialPort()
        {
            InitializeComponent();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void SerialPort_Load(object sender, EventArgs e)
        {    
            //初始化下拉串口名称列表框
            string[] ports = System.IO.Ports.SerialPort.GetPortNames();
            Array.Sort(ports);
            comboBox1.Items.AddRange(ports);  //字符串集合加入comboBox控件中
            comboBox1.SelectedIndex = comboBox1.Items.Count > 0 ? 0 : -1;   //设置控件默认值
            comboBox2.SelectedIndex = comboBox2.Items.IndexOf("9600");
            //初始化SerialPort对象
            commPort.NewLine = "\r\n";
            commPort.RtsEnable = true;//根据实际情况吧。
            commPort.Parity = Parity.None; //效验位
            commPort.DataBits = 8;  //数据位
            commPort.StopBits = StopBits.One;//停止位
            //添加事件注册
            commPort.DataReceived += comm_DataReceived;
        }

        void comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int n = commPort.BytesToRead;//先记录下来，避免某种原因，人为的原因，操作几次之间时间长，缓存不一致
            byte[] buf = new byte[n];//声明一个临时数组存储当前来的串口数据
            commPort.Read(buf, 0, n);//读取缓冲数据
            builder.Clear();//清除字符串构造器的内容
            //直接按ASCII规则转换成字符串
            builder.Append(Encoding.Default.GetString(buf));
            this.textBox1.AppendText(builder.ToString());

        }
        private void button1_Click(object sender, EventArgs e)
        {   //根据当前串口对象，来判断操作
            if (commPort.IsOpen)
            {
                commPort.Close(); //打开时点击，则关闭串口
                button1.Text = "打开串口";
            }
            else
            {
                //关闭时点击，则设置好端口，波特率后打开
                commPort.PortName = comboBox1.Text;   //端口
                commPort.BaudRate = Int32.Parse(comboBox2.Text);   //波特率
                try
                {
                    commPort.Open();
                    button1.Text = "关闭串口";
                }
                catch (Exception ex)
                {
                    //捕获到异常信息，创建一个新的comm对象，之前的不能用了。
                    commPort = new System.IO.Ports.SerialPort();
                    //现实异常信息给客户。
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void formclose(object sender, FormClosedEventArgs e)
        {
            commPort.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //定义一个变量，记录发送了几个字节
            int n = 0;
            //ascii编码直接发送,并且包含换行符
            commPort.WriteLine(textBox2.Text);
            n = textBox2.Text.Length + 2;
        }







    }
}
